import React from 'react';
import { Table, Input, Button, Form, Icon } from 'antd';

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
    <EditableContext.Provider value={form}>
        <tr {...props} />
    </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

function EditableCell(props) {
    const { editable, dataIndex, title, record, index, handleSave, children, ...restProps } = props;
    const [editing, setEditing] = React.useState(false);
    const [form, setForm] = React.useState();
    const inputRef = React.useRef();

    const toggleEdit = () => {
        setEditing(!editing);
    };

    React.useEffect(() => {
        if (editing) {
            inputRef.current.focus();
        }
    }, [editing]);

    const save = e => {
        form.validateFields((error, values) => {
            if (error && error[e.currentTarget.id]) {
                return;
            }
            toggleEdit();
            handleSave({ ...record, ...values });
        });
    };

    const renderCell = _form => {
        setForm(_form);
        return editing ? (
            <Form.Item style={{ margin: 0 }}>
                {form.getFieldDecorator(dataIndex, {
                    rules: [
                        {
                            required: true,
                            message: `${title} is required.`
                        }
                    ],
                    initialValue: record[dataIndex]
                })(<Input ref={inputRef} onPressEnter={save} onBlur={save} />)}
            </Form.Item>
        ) : (
            <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
                {children}
            </div>
        );
    };

    return (
        <td {...restProps}>
            {editable ? <EditableContext.Consumer>{renderCell}</EditableContext.Consumer> : children}
        </td>
    );
}

function EditableTable() {
    const [dataSource, setDataSource] = React.useState([
        {
            key: '0',
            name: 'Edward King 0',
            age: '32',
            address: 'London, Park Lane no. 0'
        },
        {
            key: '1',
            name: 'Edward King 1',
            age: '32',
            address: 'London, Park Lane no. 1'
        }
    ]);

    const [count, setCount] = React.useState(2);

    const handleDelete = key => {
        setDataSource(dataSource.filter(item => item.key !== key));
    };

    const columns = [
        {
            title: '2020年Q4绩效目标',
            dataIndex: 'name',
            width: '30%',
            editable: true
        },
        {
            title: '衡量标准/关键结果',
            dataIndex: 'age',
            editable: true
        },
        {
            title: '权重',
            dataIndex: 'address',
            editable: true
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (text, record) =>
                dataSource.length >= 1 ? <a onClick={() => handleDelete(record.key)}>删除</a> : null
        }
    ];

    const handleAdd = () => {
        const newData = {
            key: count,
            name: `Edward King ${count}`,
            age: 32,
            address: `London, Park Lane no. ${count}`
        };
        setDataSource([...dataSource, newData]);
        setCount(count + 1);
    };

    const handleSave = row => {
        const newData = [...dataSource];
        const index = newData.findIndex(item => row.key === item.key);
        const item = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row
        });
        setDataSource(newData);
    };

    const components = {
        body: {
            row: EditableFormRow,
            cell: EditableCell
        }
    };

    const finalColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: record => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave
            })
        };
    });

    return (
        <div>
            <Table components={components} dataSource={dataSource} columns={finalColumns} pagination={false} />
            <Button block onClick={handleAdd} style={{ marginTop: 16 }}>
                <Icon type="plus" />
                新增
            </Button>
        </div>
    );
}

export default EditableTable;
